package com.yonyou.cyxdms.basedata.service.service.salestaskset;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoleilu.hutool.bean.BeanUtil;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyx.function.utils.common.CommonUtils;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyxdms.basedata.client.domains.vo.SalesTaskSetVO;
import com.yonyou.cyxdms.basedata.service.dto.salestaskset.SalesTaskSetDTO;
import com.yonyou.cyxdms.basedata.service.entity.salestaskset.SalesTaskSetPO;
import com.yonyou.cyxdms.basedata.service.repository.salestaskset.SalesTaskSetMapper;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysmanage.client.domains.dto.UserDictDto;
import com.yonyou.cyxdms.sysmanage.client.feign.SysmanageDataCommonClient;
import com.yonyou.cyxdms.sysmanage.client.service.login.LoginService;
import com.yonyou.cyxdms.sysmanage.client.vo.user.UserInfoVO;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 销售顾问-销售任务设定（服务实现类）
 *
 * @author：chenzb
 * @since：2019-11-19
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SalesTaskSetServiceImpl extends ServiceImpl<SalesTaskSetMapper, SalesTaskSetPO> implements SalesTaskSetService {

    private static final Logger logger = LoggerFactory.getLogger(SalesTaskSetServiceImpl.class);

    @Autowired
    private LoginService loginService;

    @Autowired
    private SalesTaskSetMapper salesTaskSetMapper;

    @Autowired
    private SysmanageDataCommonClient sysManageClient;

    /**
     * 前端/查询-设置销售顾问
     *         销售任务
     * @param  consultantId,checkDate,orgId
     * @author：chenzb
     * @since：2019-11-22
     */
    @Override
    public List<SalesTaskSetVO> getConsultantSalesTaskDetail(String consultantId, String checkDate, String orgId) {
        List<String> consultants = new ArrayList<>();
        if (StringUtils.isNullOrEmpty(orgId) && !StringUtils.isNullOrEmpty(consultantId)) {
            consultants.add(consultantId);
        } else {
            // 根据OrgId获取部门下所有销售顾问Id
            logger.info("销售部门orgId:----------------{}", orgId);
            if (StringUtils.isNullOrEmpty(orgId)) {
                return Collections.emptyList();
            }
            List<UserInfoVO> userInfoVOList = sysManageClient.getUserByOrgId(orgId).getData();
            if (!CommonUtils.isNullOrEmpty(userInfoVOList)) {
                for (UserInfoVO userInfo : userInfoVOList) {
                    consultants.add(userInfo.getUserId().toString());
                }
            } else {
                return Collections.emptyList();
            }
        }
        if (CommonUtils.isNullOrEmpty(consultants)) {
            throw new ServiceBizException("当前销售小组下暂无成员！");
        }
        List<SalesTaskSetVO> consultantSalesTaskList = getConsultantSalesTaskList(consultants, checkDate);
        return CollectionUtils.isNotEmpty(consultantSalesTaskList) ? consultantSalesTaskList : null;
    }

    /**
     * 条件查询——销售顾问的任务目标
     *
     * @param consultantIds
     * @param checkDate
     * @author：chenzb
     * @since：2019-11-19
     */
    @Override
    public List<SalesTaskSetVO> getConsultantSalesTaskList(List<String> consultantIds, String checkDate) {
        if (CommonUtils.isNullOrEmpty(consultantIds) || StringUtils.isNullOrEmpty(checkDate)) {
            throw new ServiceBizException("查询条件不得为空！");
        }
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        List<SalesTaskSetVO> salesTaskSetVOList = new ArrayList<>();
        // 查询指定部门下的销售顾问的销售任务设定记录
        QueryWrapper<SalesTaskSetPO> query = new QueryWrapper<>();
        query.lambda().eq(SalesTaskSetPO::getAppId, loginInfoDto.getAppId())
                .eq(SalesTaskSetPO::getOwnerCode, loginInfoDto.getOwnerCode())
                .eq(SalesTaskSetPO::getOwnerParCode, loginInfoDto.getOwnerParCode())
                .eq(SalesTaskSetPO::getCompanyCode, loginInfoDto.getCompanyCode())
                .eq(SalesTaskSetPO::getCheckDate, checkDate)
                .eq(SalesTaskSetPO::getIsDeleted, 0)
                .in(SalesTaskSetPO::getConsultantId, consultantIds);
        List<SalesTaskSetPO> salesTaskSetPos = salesTaskSetMapper.selectList(query);
        logger.info("salesTaskSetPOs:---------{}", salesTaskSetPos);
        // 任务设定表中查询出的所有销售顾问Id的List
        List<String> noConsults = new ArrayList<>();
        if (!CommonUtils.isNullOrEmpty(salesTaskSetPos)) {
            salesTaskSetPos.forEach(salesTaskSetPo -> {
                SalesTaskSetVO salesTaskSetVO = new SalesTaskSetVO();
                BeanUtil.copyProperties(salesTaskSetPo, salesTaskSetVO);
                UserDictDto userDictDto = loginService.getUserById(Long.valueOf(salesTaskSetVO.getConsultantId()));
                if (userDictDto != null) {
                    salesTaskSetVO.setConsultantName(userDictDto.getUserName());
                }
                noConsults.add(salesTaskSetPo.getConsultantId());
                salesTaskSetVOList.add(salesTaskSetVO);
            });
            for (String consultantId : consultantIds) {
                // 表中部分销售顾问没有数据
                if (!noConsults.contains(consultantId)) {
                    getSaleTaskVoList(salesTaskSetVOList, consultantId);
                }
            }
        } else {
            // 表中销售顾问没有数据
            for (String consultantId : consultantIds) {
                getSaleTaskVoList(salesTaskSetVOList, consultantId);
            }
        }
        return !CommonUtils.isNullOrEmpty(salesTaskSetVOList) ? salesTaskSetVOList : null;
    }
    
    /**
     * 抽取后的公共方法
     * @author：chenzb
     * @since：2019-11-28
     */
    private void getSaleTaskVoList(List<SalesTaskSetVO> salesTaskSetVOList, String consultantId) {
        SalesTaskSetVO salesTaskSetVO = new SalesTaskSetVO();
        salesTaskSetVO.setConsultantId(consultantId);
        UserDictDto userDictDto = loginService.getUserById(Long.valueOf(consultantId));
        if (userDictDto != null) {
            salesTaskSetVO.setConsultantName(userDictDto.getUserName());
        }
        salesTaskSetVOList.add(salesTaskSetVO);
    }

    /**
     * 新增/更新销售顾问月销售任务
     *
     * @param salesTaskSetDTO
     * @author：chenzb
     * @since：2019-11-19
     */
    @Override
    public Integer addConstantMonthSalesTask(SalesTaskSetDTO salesTaskSetDTO) {
        logger.debug("新增/更新-销售顾问月销售任务-salesTaskSetDTO:------------{}", salesTaskSetDTO);
        if (salesTaskSetDTO == null) {
            throw new ServiceBizException("参数为空，无法更新销售任务目标");
        }
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        // 判断当前入参考核月是否已设定销售目标
        QueryWrapper<SalesTaskSetPO> query = new QueryWrapper<>();
        query.lambda().eq(SalesTaskSetPO::getAppId, loginInfoDto.getAppId())
                .eq(SalesTaskSetPO::getOwnerCode, loginInfoDto.getOwnerCode())
                .eq(SalesTaskSetPO::getOwnerParCode, loginInfoDto.getOwnerParCode())
                .eq(SalesTaskSetPO::getCompanyCode, loginInfoDto.getCompanyCode())
                .eq(SalesTaskSetPO::getConsultantId, salesTaskSetDTO.getConsultantId())
                .eq(SalesTaskSetPO::getIsDeleted,0)
                .eq(SalesTaskSetPO::getCheckDate, salesTaskSetDTO.getCheckDate());
        SalesTaskSetPO oldSalesTaskSetPo = salesTaskSetMapper.selectOne(query);
        if (oldSalesTaskSetPo != null) {
            oldSalesTaskSetPo.setCheckDate(salesTaskSetDTO.getCheckDate());
            oldSalesTaskSetPo.setFinancialRatio(salesTaskSetDTO.getFinancialRatio());
            oldSalesTaskSetPo.setLicenceRatio(salesTaskSetDTO.getLicenceRatio());
            oldSalesTaskSetPo.setInsuranceRatio(salesTaskSetDTO.getInsuranceRatio());
            oldSalesTaskSetPo.setTaskCount(salesTaskSetDTO.getTaskCount());
            oldSalesTaskSetPo.setCheckDate(salesTaskSetDTO.getCheckDate());
            logger.debug("更新之后的销售顾问的销售目标信息-oldSalesTaskSetPO:{}", oldSalesTaskSetPo);
            return salesTaskSetMapper.updateById(oldSalesTaskSetPo);
        } else {
            SalesTaskSetPO salesTaskSetPo = new SalesTaskSetPO();
            salesTaskSetPo.setAppId(loginInfoDto.getAppId());
            salesTaskSetPo.setOwnerCode(loginInfoDto.getOwnerCode());
            salesTaskSetPo.setCompanyCode(loginInfoDto.getCompanyCode());
            salesTaskSetPo.setOwnerParCode(loginInfoDto.getOwnerParCode());
            BeanUtil.copyProperties(salesTaskSetDTO, salesTaskSetPo);
            logger.debug("待新增的销售顾问的销售目标信息-salesTaskSetPO:{}", salesTaskSetPo);
            return salesTaskSetMapper.insert(salesTaskSetPo);
        }
    }
}
